<template>
  <div class="contain-edit">
    <div class="header">
      <p>租房管理/新增房客</p>
      <el-button class="link" type="primary">
        <router-link to="/houseList" style="color: #fff;">返回</router-link>
      </el-button>
    </div>
    <div class="main">
      <el-form :model="information" :rules="rules" ref="information" label-width="160px" class="">

      <div class="flex-box-container">
        <div class="flex">
            <el-form-item label="租客：" prop="name">
              <el-input v-model="information.name" placeholder="请输入"></el-input>
            </el-form-item>
            <el-form-item label="身份证：" prop="idCardNo">
              <el-input v-model="information.idCardNo" placeholder="请输入"></el-input>
            </el-form-item>
        </div>
        <div class="flex">
            <el-form-item label="性别：" prop="sex">
              <el-select v-model="information.sex" placeholder="请选择">
                <el-option
                  v-for="item in sexList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="联系电话：" prop="mobile">
             <el-input v-model="information.mobile" placeholder="请输入"></el-input>
            </el-form-item>
        </div>
      </div>
        <el-form-item label="租客身份证正反面：" prop="idcardkey1">
                <el-upload  list-type="picture-card"
                    :action="upLoadUrl"
                    :class="{uploadShow:fileShowList.length>=2}"
                    :file-list='fileShowList'
                    :on-remove="handleRemove"
                    :before-upload="beforePicsUpload"
                    :limit="2">
                    <i class="el-icon-plus"></i>
                </el-upload>
        </el-form-item>
        <div class="flex-box-container">
          <div class="flex">
            <el-form-item label="租客类型：" prop="rentalType">
              <el-select v-model="information.rentalType" placeholder="请选择">
                <el-option
                  v-for="item in rentalTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="紧急联系人：" prop="renterEmergencycontact">
              <el-input v-model="information.renterEmergencycontact" placeholder="请输入"></el-input>
            </el-form-item>
          </div>
          <div class="flex">
            <el-form-item label="入住时间：" prop="rentalCheckin">
              <el-date-picker
                v-model="information.rentalCheckin"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="紧急联系人电话：" prop="renterEmergencymobile">
              <el-input v-model="information.renterEmergencymobile" placeholder="请输入"></el-input>
            </el-form-item>
          </div>
        </div>
        <div class="arr-group">
            <div class="tip-bold">
              同住人信息
              <!--<i class="el-icon-remove-outline"></i>-->
              <el-button style="margin-left: 20px;" type="primary" size="mini" icon="el-icon-circle-plus-outline" @click="handleAddPartner">添加</el-button>
            </div>
            <div v-for="(item, index) in partnerInfo" :key="index" style="padding: 20px 0;border-bottom: 1px solid #eee;">
              <el-form-item label="同住人：" prop="title">
                <el-input v-model="item.name" placeholder="请输入"></el-input>
              </el-form-item>
              <el-form-item label="性别：" prop="title">
                <el-select v-model="item.sex" placeholder="请选择">
                  <el-option
                    v-for="item in sexList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="联系电话：" prop="title">
                <el-input v-model="item.mobile" placeholder="请输入"></el-input>
              </el-form-item>
              <el-form-item label="同住人身份证正反面：" prop="title">
                <el-upload  list-type="picture-card"
                            :action="upLoadUrl"
                            :class="{uploadShow: item.fileShowList && item.fileShowList.length>=2 ? true : false}"
                            :file-list='item.fileShowList'
                            :on-remove="handleRemove1.bind(null, index)"
                            :before-upload="beforePicsUpload1.bind(null, index)"
                            :limit="2">
                  <i class="el-icon-plus"></i>
                </el-upload>
              </el-form-item>
              <el-button type="danger" icon="el-icon-delete" style="margin-left: 160px;padding: 6px 20px" v-if="partnerInfo.length != 1" @click="handleDelPartner(index)">删除</el-button>
            </div>
        </div>
        <div class="arr-group" style="padding: 20px 0;">
          <div class="tip-bold">
            填写合同信息
          </div>
          <div class="flex-box-container">
            <div class="flex">
                <el-form-item label="地址：" prop="">
                  <el-input disabled v-model="information.address" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="租赁开始时间：" prop="rentalCheckin">
                  <el-input v-model="information.rentalCheckin" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="押金：" prop="rentalDeposit">
                  <el-input v-model="information.rentalDeposit" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="缴租日期：" prop="rentalRentday">
                  <el-input v-model.number="information.rentalRentday" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="电单价：" prop="rentalElectricprice">
                  <el-input v-model="information.rentalElectricprice" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="当前水表读数：" prop="rentalWaterreadouts">
                  <el-input v-model.number="information.rentalWaterreadouts" placeholder="请输入"></el-input>
                </el-form-item>
            </div>
            <div class="flex">
                <el-form-item label="租赁用途：" prop="rentalUsage">
                  <el-select v-model="information.rentalUsage" placeholder="请选择">
                    <el-option
                      v-for="item in useList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="租赁结束时间：" prop="rentalCheckout">
                  <el-date-picker
                    v-model="information.rentalCheckout"
                    type="date"
                    placeholder="选择日期"
                    value-format="yyyy-MM-dd">
                  </el-date-picker>
                </el-form-item>
                <el-form-item label="租金（月）：" prop="rentalRentprice">
                  <el-input v-model.number="information.rentalRentprice" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="水单价：" prop="rentalWaterprice">
                  <el-input v-model.number="information.rentalWaterprice" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="当前电表读数：" prop="rentalElectricreadouts">
                  <el-input v-model.number="information.rentalElectricreadouts" placeholder="请输入"></el-input>
                </el-form-item>
                <el-form-item label="乙方需要自行支付的杂费项目：" prop="rentalOtherfeeitem">
                  <el-tag
                    :key="tag"
                    v-for="tag in otherfeeList"
                    closable
                    :disable-transitions="false"
                    @close="handleCloseTag(tag)">
                    {{tag}}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="inputVisible"
                    v-model="inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm"
                    @blur="handleInputConfirm"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput">自定义添加</el-button>
                </el-form-item>
            </div>
          </div>
        </div>
        <el-dialog
          title="合同签字"
          :visible.sync="dialogVisible"
          :before-close="handleClose">
          <div>
            <Canvas :signKey="signKey" @getSignKey="getSignKey"></Canvas>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="submitForm('information')">确 定</el-button>
          </span>
        </el-dialog>

        <el-form-item style="margin-top: 20px;">
          <el-button type="primary" @click="handlePub"  :loading="loading">去签字</el-button>
          <el-button @click="back()">返回</el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>
</template>

<script>
  let CONSTANT = require('../../constant/constant.js');
  let common = require("../../common.js");
  import $ from 'jquery'
  import $axios from 'axios'
  export default {
    data() {
      var validateNumber =  (rule, value, callback) => {
        var reg = /^[1][3,4,5,8][0-9]{9}$/;
        if (!reg.test(value)){ return callback(new Error('手机号格式有误')); }
        return callback();
      };

      var validateCode =  (rule, value, callback) => {
        var reg = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
        if (!reg.test(value)){ return callback(new Error('身份证号格式有误')); }
        return callback();
      };


      return {
        id:null,
        buildList: [],
        imagesList: [],
        images1List: [],
        fileShowList: [],
        fileShowList1: [],
        upLoadUrl: "",
        information:{
          rentalLandlordSignKey:'',
          rentalCheckin: "",
          rentalCheckout: "",
          rentalDeposit: "",
          rentalElectricprice: "",
          rentalElectricreadouts: "",
          rentalOtherfeeitem: "",
          rentalRentday: "",
          rentalRentprice: "",
          rentalUsage: "",
          rentalWaterprice: "",
          rentalWaterreadouts: "",
          renterEmergencycontact:"",
          renterEmergencymobile: "",
          rentalContract: "",

          idCardNo: "",
          idcardkey1: "",
          idcardkey2: "",
          mobile: "",
          name: "",
          renterType: "",
          sex: ""
        },
        partnerInfo: [{
          idCardNo: "",
          idcardkey1: "",
          idcardkey2: "",
          mobile: "",
          name: "",
          renterType: "",
          sex: "",
          fileShowList: [],
          imagesList: []
        }],
        paramsDict: {},
        useList: [{
          label: "住房",
          value: "住房"
        },{
          label: "商铺",
          value: "商铺"
        }],
        rules: {
          'name': [
            {required: true, message: '请输入租客姓名', trigger: 'blur'}
          ],
          'mobile': [
            {required: true, message: '请输入联系电话', trigger: 'blur'},
            {  validator: validateNumber, trigger: 'blur' }
          ],
          'sex': [
            {required: true, message: '请选择性别', trigger: 'blur'}
          ],
          'idCardNo': [
            {required: true, message: '请输入身份证号', trigger: 'blur'},
            {  validator: validateCode, trigger: 'blur' }
          ],
          'idcardkey1': [
            {required: true, message: '请上传租客身份证', trigger: 'blur'}
          ],
          rentalDeposit: [
            {required: true, message: '请输入押金', trigger: 'blur'}
          ],
          rentalElectricreadouts: [
            {required: true, message: '请输入电表读数', trigger: 'blur'},
            { type: 'number', message: '电表读数必须为数字值'}
          ],
          rentalWaterreadouts: [
            {required: true, message: '请输入水表读数', trigger: 'blur'},
            { type: 'number', message: '水表读数必须为数字值'}
          ],
          rentalCheckin: [
            { required: true, message: '请选择入住日期', trigger: 'blur' },
          ],
          rentalCheckout: [
            { required: true, message: '请选择退租日期', trigger: 'blur' },
          ],
          renterEmergencycontact: [
            { required: true, message: '请输入紧急联系人', trigger: 'blur' }
          ],
          renterEmergencymobile: [
            { required: true, message: '请输入紧急联系人电话号码', trigger: 'blur' },
            {  validator: validateNumber, trigger: 'blur' }
          ],
          rentalType: [
            { required: true, message: '请选择租客类型', trigger: 'blur' }
          ],
          rentalWaterprice: [
            { required: true, message: '请输入水费单价', trigger: 'blur' }
          ],
          rentalElectricprice: [
            { required: true, message: '请输入电费单价', trigger: 'blur' }
          ],
          rentalOtherfeeitem: [
            { required: true, message: '请输入杂费项目', trigger: 'blur' }
          ],
          rentalRentday: [
            { required: true, message: '请输入缴租时间', trigger: 'blur' },
            { type: 'number', message: '缴租时间必须为数字值'}
          ],
          rentalRentprice: [
            { required: true, message: '请输入租金', trigger: 'blur' },
            { type: 'number', message: '租金必须为数字值'}
          ],
          rentalUsage: [
            { required: true, message: '请输入租赁用途', trigger: 'blur' }
          ],
//          rentalRentprice: [
//            { required: true, message: '请输入租金', trigger: 'blur' }
//          ],
          rentalContract: [
            { required: true, message: '请输入合同信息', trigger: 'blur' }
          ]
        },
        loading: false,
        sexList: [{
          label: "男",
          value: "male"
        },{
          label: "女",
          value: "female"
        },{
          label: "中性",
          value: "unknow"
        }],
        rentalTypeList: [{
          label: "日租",
          value: "day_rental"
        },{
          label: "长租",
          value: "long_rental"
        },{
          label: "年租",
          value: "year_rental"
        }],
        otherfeeList:[],
        inputVisible: false,
        inputValue: '',
        dialogVisible: false,
        signKey: "",
        identify: ""
      };
    },
    components: {
      'Canvas': () => import("../common/Canvas"),
      'Sign': () => import("../common/sign")
    },
    created() {
    },
    mounted() {
      this.identify = sessionStorage.getItem("identify");
      this.id  = this.$router.currentRoute.query.id;
      this.information.landlordName = sessionStorage.getItem("manager")
      if(this.id){
        this.getDetail();
      }
    },
    methods: {
      back(){this.$router.push('/houseList');},
      getDetail(){
        let url = this.identify == 1 ? CONSTANT.URL.HOUSE.DETAIL : CONSTANT.URL.L_HOUSE.DETAIL;
        let data = {
          id:this.id
        } ;
        common.requestAjax(url, {}, data, (res)=>{
          let d = res.data.bussData;

          this.information = {
            address: d.address,
            unitName: d.unitName,
            gardenName: d.gardenName,
            roomNo: d.roomNo,
            buildName: d.buildName,
            publicAllocate: d.publicAllocate,
            otherAllocate: d.otherAllocate,
            houseAllocate: d.houseAllocate,
            imagesKey: d.imagesKey,
            deposit: d.deposit,
            roomType: d.roomType,
            toward: d.toward,
            memo: d.memo,
            floor: d.floor,
            area: d.area,
            cleaningFee: d.cleaningFee,
            gasFee: d.gasFee,
            healthFee: d.healthFee,
            internetFee: d.internetFee,
            managementFee: d.managementFee,
            electricRate: d.electricRate,
            waterRate: d.waterRate,
            dayRent: d.dayRent,
            longRent: d.longRent,
            yearRent: d.yearRent,
            landlordName: d.landlordName
          }
        })
      },
      handleDelPartner(index) {
        this.partnerInfo.splice(index, 1)
      },
      handlePub() {
//        this.$message({
//          type: "warning",
//          message: "请合同签字"
//        })
//        setTimeout( () => {
          this.dialogVisible = true
//        }, 3000)
      },
      getSignKey(e) {
        this.information.rentalLandlordSignKey = e
      },
      submitForm(formName) {
        if (!this.information.rentalLandlordSignKey) {
          this.$message({
            type: "warning",
            message: "请签名"
          })
          return false;
        }

        if (!this.imagesList[1]) {
          this.$message({
            type: "warning",
            message: "请上传租客的反面身份证照片"
          })
          this.dialogVisible = false
          return false;
        }
        this.information.idcardkey1 = this.imagesList[0]
        this.information.idcardkey2 = this.imagesList[1]
        this.information.renterType = "major"

        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.loading = true;

            this.paramsDict = {
              rentalCheckin: this.information.rentalCheckin,
              rentalCheckout: this.information.rentalCheckout,
              rentalElectricreadouts: this.information.rentalElectricreadouts,
              rentalElectricprice: this.information.rentalElectricprice,
              rentalWaterprice: this.information.rentalWaterprice,
              rentalWaterreadouts: this.information.rentalWaterreadouts,
              renterEmergencycontact: this.information.renterEmergencycontact,
              renterEmergencymobile: this.information.renterEmergencymobile,
              rentalRentprice: this.information.rentalRentprice,
              rentalUsage: this.information.rentalUsage,
              rentalRentday: this.information.rentalRentday,
              rentalDeposit: this.information.rentalDeposit,
              rentalOtherfeeitem: this.information.rentalOtherfeeitem,
              rentalContract: this.information.rentalContract ? this.information.rentalContract : '',
              rentalLandlordSignKey: this.information.rentalLandlordSignKey,
              rentalType: this.information.rentalType,
              rentalRenters: [{
                idCardNo: this.information.idCardNo,
                idcardkey1: this.imagesList[0],
                idcardkey2: this.imagesList[1],
                mobile: this.information.mobile,
                name: this.information.name,
                renterType: "major",
                sex: this.information.sex
              }]
            }

            if (this.partnerInfo.length) {
              let paramsArr = [];
              this.partnerInfo.map( (item, index) => {
                this.paramsDict.rentalRenters.push({
                  idCardNo: item.idCardNo,
                  mobile: item.mobile,
                  name: item.name,
                  renterType: "partner",
                  sex: item.sex,
                  idcardkey1: item.imagesList && item.imagesList.length ? item.imagesList[0] : "",
                  idcardkey2: item.imagesList && item.imagesList.length && item.imagesList.length > 1 ? item.imagesList[1] : "",
                })
              })
            }

            let url = CONSTANT.URL.L_RENTAL.CREATE
            let param = JSON.stringify(Object.assign(this.paramsDict, {houseId: this.id}));
            common.requestAjax(url, param, null, res => {
              if(res.status == 200) {
                this.$message({
                  type: 'success',
                  message: res.msg
                });
                this.loading = false;
                this.$router.push("/houseList");
              } else {
                this.$message({
                  type: 'error',
                  message: res.msg
                });
                this.dialogVisible = false
                this.loading = false;
              }
            });
          } else {
            this.dialogVisible = false
            return false;
          }
        });
      },
      beforePicsUpload(file) {
        let url =CONSTANT.URL.COMMON.UPLOAD;
        let param = {
          suffix:file.name.split(".")[1],   // 文件后缀  png
          contentType:file.type             // 文件类型  image/png
        }
        common.requestAjax(url,param,null,(res)=> {
          this.upLoadUrl = res.data.bussData.uploadUrl;
          this.imagesList.push(res.data.bussData.fileKey)

          let downloadUrl = res.data.bussData.downloadUrl;
          common.uploadFile(this.upLoadUrl,file,file.type,(res)=>{
            this.fileShowList.push({
              url:downloadUrl
            })
          })
        });
      },
      beforePicsUpload1(index, file) {
        let url =CONSTANT.URL.COMMON.UPLOAD;
        let param = {
          suffix:file.name.split(".")[1],   // 文件后缀  png
          contentType:file.type             // 文件类型  image/png
        }
        common.requestAjax(url,param,null,(res)=> {
          this.upLoadUrl = res.data.bussData.uploadUrl;
          this.partnerInfo[index].imagesList.push(res.data.bussData.fileKey)

          let downloadUrl = res.data.bussData.downloadUrl;
          common.uploadFile(this.upLoadUrl,file,file.type,(res)=>{
            this.partnerInfo[index].fileShowList.push({
              url:downloadUrl
            })
          })
        });
      },
      handleRemove(file, fileList) {
        let arr = []
        let deleteUrl = file.url;
        let list = this.fileShowList;
            list.forEach((item,index)=>{
                if(item.url == deleteUrl){
                    list.splice(index,1);
                }
            })
        fileList.map( (item, index) => {
          arr.push(item.url.split("com/")[1])
        })
        this.imagesList = arr
      },
      handleRemove1(index, file, fileList) {
        let arr = []
        let deleteUrl = file.url;
        let list = this.partnerInfo[index].fileShowList;
        list.forEach((item,index)=>{
          if(item.url == deleteUrl){
            list.splice(index,1);
          }
        })
        fileList.map( (item, index) => {
          arr.push(item.url.split("com/")[1])
        })
        this.partnerInfo[index].imagesList = arr
      },

      handleAddPartner() {
        this.partnerInfo.push({
          idCardNo: "",
          idcardkey1: "",
          idcardkey2: "",
          mobile: "",
          name: "",
          renterType: "",
          sex: "",
          fileShowList: [],
          imagesList: []
        })
      },

      handleClose() {
        this.dialogVisible = false
      },

      handleCloseTag(tag) {
        this.otherfeeList.splice(this.otherfeeList.indexOf(tag), 1);
        this.information.rentalOtherfeeitem = this.otherfeeList.join(",")
      },

      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      handleInputConfirm() {
        let inputValue = this.inputValue;
        if (inputValue) {
          this.otherfeeList.push(inputValue);
          this.information.rentalOtherfeeitem = this.otherfeeList.join(",")
        }
        this.inputVisible = false;
        this.inputValue = '';
      },

      handleAreaChange() {
        let url = this.identify == 1 ? CONSTANT.URL.BUILDING.FINDLIST : CONSTANT.URL.L_BUILDING.FINDLIST,
            params = {
              parentId: this.areaId
            }
        common.requestAjax(url, JSON.stringify(params), {}, (data) => {
          if (data.status == 200) {
            this.unitList = []
            this.buildList = []
            this.unitId = ""
            this.information.buildingId = ""
            data.data.bussData.map( item => {
              this.unitList.push({
                label: item.name,
                value: item.id
              })
            })

          }
        })
      },
      handleUnitChange() {
        let url = this.identify == 1 ? CONSTANT.URL.BUILDING.FINDLIST : CONSTANT.URL.L_BUILDING.FINDLIST,
          params = {
            parentId: this.unitId
          }
        common.requestAjax(url, JSON.stringify(params), {}, (data) => {
          if (data.status == 200) {
            this.buildList = []
            this.information.buildingId = ""
            data.data.bussData.map( item => {
              this.buildList.push({
                label: item.name,
                value: item.id
              })
            })
          }
        })
      }
    }
  }
</script>

<style lang="scss" scoped >
  @import '/static/bootstrap.css';
  @import '/sys/static/bootstrap.css';
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  ul, li {
    list-style: none;
  }
  .house-allocate {
    li {
      margin-bottom: 20px;
      span {
        width: 60px;
        display: inline-block;
      }
    }
  }
  .el-form-item__content{
    margin-left: 0;
  }
  .arr-group{
      .tip-bold{
          font-size: 14px;
          font-weight: bold;
          width: 400px;
          margin-left: 7.8%;
          margin-bottom: 30px;
          i{
              position: relative;
              top: 2px;
              cursor: pointer;
              font-size: 18px;
              margin-left: 10px;
              margin-right: 30px;
          }
      }
  }
  .avatar-uploader {
    border-radius: 6px;
    box-sizing: border-box;
    vertical-align: top;
    .el-upload {
      cursor: pointer;
      position: relative;
      overflow: hidden;
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
        border: 1px dashed #d9d9d9 !important;
        border-radius: 6px;
        margin-left: 6px;
      }
      .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
    }
    .el-upload:hover {
      border-color: #20a0ff;
    }
  }
</style>
